//
//  SSDKHttpV2Util.m
//  SuperSDK
//
//  Created by 涂俊 on 2017/10/30.
//  Copyright © 2017年 WYHT. All rights reserved.
//

#import "SSDKHttpV2Util.h"
#import "SuperSDKInst.h"
#import "SuperSDKPluginTools/SSDKPluginHttpUtil.h"
#import "SuperSDKPluginTools/SSDKPluginJsonUtil.h"
#import "SUperSDKPluginTools/SSDKPluginEncryptUtil.h"


@implementation SSDKHttpV2Util

/**
 * 将所有参数计算md5签名，请求服务器端。
 * 判断返回的status字段，判断出请求结果是否成功。
 */
+ (void) postWithUrl : (NSString *) url
                data : (NSDictionary *) params
        httpDelegate : (void (^)(BOOL status, NSDictionary* resData))delegate {
    NSMutableDictionary *wrapParams = [[NSMutableDictionary alloc] initWithDictionary:params];
    [wrapParams setObject:[[SuperSDKInst getInstance] appId] forKey:@"app_id"];
    [self calSign:wrapParams];
    
    [SSDKPluginHttpUtil postWithUrl:url data:wrapParams delegate:^(BOOL networkAvaliable, NSInteger status, NSString *resData) {
        // TODO...
        NSLog(@"post,url=%@,status=%ld,httpResponse=%@", url, (long)status, resData);
        if (!networkAvaliable) {
            NSLog(@"post网络不可用!url=%@", url);
            if (delegate != nil) {
                delegate(NO, nil);
            }
            return;
        }
        NSMutableDictionary *resDic = nil;
        if (200 == status) {
            @try {
                resDic = [SSDKPluginJsonUtil toObjectWithJson:resData];
            }
            @catch (NSException *exception) {
                NSLog(@"post返回处理异常,exception=%@,reason=%@", exception.name, exception.reason);
            }
        }
        if (resDic == nil || [resDic count] == 0) {
            NSLog(@"post返回为空!url=%@", url);
            if (delegate != nil) {
                delegate(NO, nil);
            }
            return;
        }
        NSString *retStatus = [resDic valueForKey:@"status"];
        if (delegate != nil) {
            delegate([@"ok" isEqualToString:retStatus], resDic);
        }
    }];
}

// 给参数集合计算签名，并以"sign"作为key添加回参数集合
+ (void) calSign:(NSMutableDictionary *) params {
    NSString *sign = [SSDKPluginEncryptUtil generateSignWithDictionary:params
                                                            useSignKey:[[SuperSDKInst getInstance] appSecret]];
    [params setObject:sign forKey:@"sign"];
}

@end
